<?php
namespace api\toilet\controller;

use api\admin\model\BandToiletModel;
use api\admin\model\ToiletModel;
use cmf\controller\RestBaseController;
use think\Db;

class IndexController extends RestBaseController
{

    /**
     * [toiletDetails 获取当前列表]
     * @Author   HUI
     * @DateTime 2018-12-04
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function toiletlist($value = '')
    {   

        $toiletRes = null;
        // $code = $this->request->param('code');
        $param = $this->request->param();
        $pageSize = !empty($param['page_size'])? $param['page_size']: 10;

        if ($param['code']) {
            $user = DB::name('user')->where('user_code', $param['code'])->find();
            if (!empty($user)) {
                $Toilet = new ToiletModel();
                $toiletRes = $Toilet
                ->field('title,mac,id')
                ->where(['user_id' => $user['id'], 'status' => 1])
                ->paginate($pageSize);
            }
        }
        return $this->success('列表获取成功', $toiletRes);
    }

    /**
     * [toiletDetails 获取当前公厕详情]
     * @Author   HUI
     * @DateTime 2018-12-04
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function toiletDetails($value = '')
    {
        $mac = $this->request->param('mac');
        if ($mac) {
            $Toilet = new ToiletModel();
            $toiletRes = $Toilet->getToiletFields(['mac' => $mac, 'status' => 1]);
            return $this->success('详情获取成功', ['details' => $toiletRes]);
        }
    }

    /**
     * [flow 流量统计]
     * @Author   HUI
     * @DateTime 2018-12-04
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function flow($value = '')
    {
        $param = $this->request->param();
        $xml = file_get_contents('php://input'); //PHP7接收
        file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/upload/flowxml.txt", json_encode($xml) . PHP_EOL, FILE_APPEND);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/upload/flow.txt", json_encode($data) . PHP_EOL, FILE_APPEND);
        file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/upload/flows.txt", json_encode($param) . PHP_EOL, FILE_APPEND);
        if (!empty($data)) {
            if (isset($data['macAddress']) && !empty($data['macAddress'])) {
                $mac = str_replace(':', '', $data['macAddress']);
                $BandToilet = new BandToiletModel();
                $toiletRes = $BandToilet->getBandToiletFields(['mac' => $mac]);
                if (!empty($toiletRes)) {
                    $RedisKey = $this->getRedisKey($toiletRes);
                    $redis = new \Redis();
                    $redis->connect('127.0.0.1', 6379);
                    //今日流量
                    if (substr_compare($data['peopleCounting']['TimeRange']['startTime'], '00:00:00+08:00', -14) === 0) {
                        $redis->set($RedisKey . '_today_flow', 0);
                    }
                    $Flow['today'] = $redis->incr($RedisKey . '_today_flow', (int)$data['peopleCounting']['enter']);
                    //累计流量
                    $Flow['all'] = $redis->incr($RedisKey . '_all_flow', (int)$data['peopleCounting']['enter']);
                    $redis->hset($RedisKey, trim($toiletRes['mac']), serialize($Flow));
                    $redisResult = $redis->hgetall($RedisKey);
                    $redis->hset('cloud_' . $toiletRes['master_mac'], trim($RedisKey), serialize($redisResult)); 
                    $redis->hset('cloud_' . $toiletRes['master_mac'], 'cloud_' . $toiletRes['master_mac'] . '_other_flow', serialize($redisResult));
                }
            }
        }
    }

    public function getRedisKey($array = [])
    {

        // cloud_mac 此MAC所有信息
        // cloud_mac_device 此MAC设备类型下的所有信息
        // cloud_mac_device_man 此MAC设备类型男厕下的所有信息
        // cloud_mac_device_man_mini[mac] 此MAC设备类型男厕下单设备的信息
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $mac_device_type = ['flow', 'device', 'sensor'];
        $Tag = $redis->get('toiletTag');
        foreach (unserialize($Tag) as $key => $value) {
            if ($array['tag_id'] == $value['id']) {
                $device = $value;
            }
        }
        if (empty($device)) {
            return 0;
        }
        //1.tag写入缓存
        //2.主设备状态写入缓存 5min
        //2.单设备状态写入缓存 5min
        return 'cloud_' . $array['master_mac'] . '_' . $mac_device_type[$array['mac_device_type'] - 1] . '_' . $device['tag_as_name'];
    }

    /**
     * [getCityWeather 获取天气]
     * @Author   HUI
     * @DateTime 2018-12-06
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getCityWeather($value = '')
    {

        $host = "https://ali-weather.showapi.com";
        $path = "/phone-post-code-weeather";
        $method = "GET";
        $appcode = "5dedbaeadbae494dbf4731402540408d";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0&post_code=1012600";
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $response = (curl_exec($curl));
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $weatherRes = substr($response, $headerSize);
        print_r($weatherRes);exit();
        // $this->success('获取天气成功', ['weathesr' => $weatherRes]);

    }

    /**
     * [strToarray 字符串转数组]
     * @Author   HUI
     * @DateTime 2018-12-06
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function strToarray($value = '')
    {
        $tmp = explode('}', $value);
        foreach ($tmp as $key => $value) {
            $strTmp = explode(':', $value);
            $tmps = explode('~', $strTmp[1]);
            $cityCode = str_replace('"', '', trim($tmps[0]));
            if (!empty($cityCode)) {
                break;
            }
        }
        return $cityCode;
    }

    public function delHash($value = '')
    {
        $mac = $this->request->param('mac');
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $data = $redis->hgetall('cloud_00ff2c2c2c6a6f005f94');
        print_r($data);
        exit();
        foreach ($data as $key => $value) {
            $dataTmp = $redis->hgetall($key);
            foreach ($dataTmp as $k => $v) {
                $redis->hdel($key, $k);
            }
            $redis->hdel('cloud_' . $mac, $key);
        }
    }

    public function getValues($value = ''){
        $mac = $this->request->param('mac');
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $result = $redis->hgetall('cloud_' . $mac); //
        if (!empty($result)) {
            foreach ($result as $key => $value) {
                $toiletTmp = @unserialize($value);
                if(!empty($toiletTmp)){
                    foreach ($toiletTmp as $k => $v) {

                        if (!empty($k)) {
                            $tmp = @unserialize($v);
                            if (substr_count($key,'device')) {
                                $toilet[$key][$k]['zsta'] = isset($tmp['zsta']) ? $tmp['zsta']  : 0;
                                $toilet[$key][$k]['order'] = $tmp['order'];
                            } else {
                                $toilet[$key][$k] = $tmp;
                            }
                        }
                    }
                }
            }
            foreach ($toilet as $key => $value) {
                if (substr_count($key, 'device')) {
                    @array_multisort(array_column($value, 'order'), SORT_ASC, $value);
                }
                $keys = str_replace('cloud_' . $mac . '_', '', $key);
                $toilets[$keys] = array_values($value);
            }
            // print_r($toilet);exit();
            return $toilet;
        }
    }







    /**
     * [getWeather 根据邮编获取天气状况]
     * @param  [type] $postCode [description]
     * @return [type]           [description]
     */
    public function getWeather()
    {

        $param = $this->request->param();

        $toilet = new ToiletModel();
        $postCode = $toilet->where(['mac'=>$param['mac'],'status'=>1])->value('post_code');
        if (!$postCode) {
            $postCode = '100020';
            // return $this->success('获取成功', $weatherRes);
        }

        $host    = "https://ali-weather.showapi.com";
        $path    = "/phone-post-code-weeather";
        $method  = "GET";
        $appcode = "5dedbaeadbae494dbf4731402540408d";
        $headers = [];
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0&post_code=" . $postCode;
        $bodys  = "";
        $url    = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $response   = (curl_exec($curl));
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header     = substr($response, 0, $headerSize);
        $weatherRes = substr($response, $headerSize);
        $weatherRes = json_decode($weatherRes, true);
        if ($weatherRes['showapi_res_body']['ret_code'] != 0)
        {
            $weatherRes = null;
        }
        return $this->success('获取成功', $weatherRes);

    }
    

}
